import React from 'react';
import { Modal, Form, Input, Checkbox, Select, TimePicker } from 'antd';
import { Row, Col, message } from 'antd';
import dayjs from 'dayjs';

import TimeDeltaPicker from './TimeDeltaPicker'

import intl from '../intl'
import { ReportType } from '../core/common'
import SparkChannel from '../ipc/sparkchannel'

const generate_time_format = 'HH:mm';

class SettingDialog extends React.Component {
  constructor(props) {
    super(props);

    this.handleSubmit = this.handleSubmit.bind(this);
    this.onFinish = this.onFinish.bind(this);
    this.onFinishFailed = this.onFinishFailed.bind(this);
    this.onValuesChange = this.onValuesChange.bind(this);

    this.formRef = React.createRef();

    const report = this.props.report;
    this.state = {
      nodeOptions: [],
      autoGenerateEnabled: report.auto_generate || false,
      confirmLoading: false,
    }
  }

  componentDidMount() {
    SparkChannel().then(channel => {
      return channel.request_get_sys_node_list();
    }).then(resp => {
      const node_list = resp.data.node_list;
      const options = node_list.map(n => {
        const name = n.node_desc;
        return { value: name, label: name, };
      });

      this.setState({
        nodeOptions: options,
      });
    }).catch((err) => {
      console.log('Got node list fail', err);
      message.error('获取系统节点列表失败');
    });
  }

  handleSubmit() {
    this.formRef.current.submit();
  }
  onFinish(values) {
    console.log('Success:', values);
    const config = {
      "book_type": this.props.config.book_type,
      "zero": Boolean(values.zero),
      "input_username": Boolean(values.input_username),
      "custom_time_range": Boolean(values.custom_time_range),
      "begin_delta": values.begin_delta,
      "end_delta": values.end_delta,
    };
    const report = this.props.report;
    const bookType = ReportType.getById(report.report_type);
    let autoGenerateConfig;
    if (bookType.value === 'DAY') {
      const { auto_generate, generate_time, generate_node, generate_path, generate_subdirectory } = values;
      autoGenerateConfig = {
        auto_generate,
        generate_time: generate_time && generate_time.format(generate_time_format),
        generate_node,
        generate_path,
        generate_subdirectory
      };
    }

    const result = this.props.onSubmit(config, autoGenerateConfig);
    if (result instanceof Promise) {
      this.setState({ confirmLoading: true });
      result.finally(() => {
        this.setState({ confirmLoading: false });
      });
    }
  };
  onFinishFailed(errorInfo) {
    console.log('Failed:', errorInfo);
  };

  onValuesChange(changedValues, allValues) {
    console.log('onValuesChange', changedValues, allValues);
    if ('auto_generate' in changedValues) {
      this.setState({ autoGenerateEnabled: changedValues.auto_generate });
    }
  };

  render() {
    const state = this.state;
    const { report, config, open, onCancel } = this.props;
    const bookType = ReportType.getById(report.report_type);
    const initialValues = {
      book_type: bookType && bookType.label,
      begin_delta: config.begin_delta,
      end_delta: config.end_delta,
      zero: config.zero,
      input_username: config.input_username,
      custom_time_range: config.custom_time_range,
    };
    const isDayReport = bookType && bookType.value === 'DAY';
    if (isDayReport) {
      Object.assign(initialValues, {
        auto_generate: report.auto_generate,
        generate_time: report.generate_time && dayjs(report.generate_time, generate_time_format),
        generate_node: report.generate_node,
        generate_path: report.generate_path,
        generate_subdirectory: report.generate_subdirectory,
      });
    }

    const autoGenerateItems = (
      <>
        <Form.Item
          label="自动生成"
          name="auto_generate"
          valuePropName="checked">
          <Checkbox />
        </Form.Item>
        {/* <Divider orientation="left" plain={true}>自动生成</Divider> */}
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label='生成节点'
              name="generate_node">
              <Select options={state.nodeOptions} disabled={!state.autoGenerateEnabled} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="生成时间"
              name="generate_time">
              <TimePicker format={generate_time_format} disabled={!state.autoGenerateEnabled} />
              {/* <Input type="text" /> */}
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item
              label="生成目录"
              name="generate_path">
              <Input type="text" disabled={!state.autoGenerateEnabled} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="按日期生成子目录"
              name="generate_subdirectory"
              valuePropName="checked">
              <Checkbox disabled={!state.autoGenerateEnabled} />
            </Form.Item>
          </Col>
        </Row></>
    );


    return (
      <Modal title="模板参数配置"
        width={600}
        zIndex={1020}
        open={open}
        confirmLoading={state.confirmLoading}
        onCancel={onCancel}
        onOk={this.handleSubmit}>
        <Form
          colon={false}
          ref={this.formRef}
          onValuesChange={this.onValuesChange}
          onFinish={this.onFinish}
          onFinishFailed={this.onFinishFailed}
          initialValues={initialValues}>

          <Form.Item
            label="报表类型"
            name="book_type">
            <Input type="text" disabled />
          </Form.Item>

          <Form.Item
            label={intl.messages.label_delta_time}
            tooltip={intl.messages.tooltip_delta_time}>
            <Form.Item
              name="begin_delta"
              style={{
                display: 'inline-block',
                marginBottom: 0,
              }}>
              {/* <TimePicker format="HH:mm" placeholder="开始时间" /> */}
              <TimeDeltaPicker placeholder="开始时间" />
            </Form.Item>
            <span style={{
              display: 'inline-block',
              width: '24px',
              lineHeight: '32px',
              textAlign: 'center',
            }} > - </span>
            <Form.Item
              name="end_delta"
              style={{
                display: 'inline-block',
                marginBottom: 0,
              }}>
              {/* <TimePicker format="HH:mm" placeholder="结束时间" /> */}
              <TimeDeltaPicker placeholder="结束时间" />
            </Form.Item>
          </Form.Item>
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item
                label={intl.messages.label_zero}
                tooltip={intl.messages.tooltip_zero}
                name="zero"
                valuePropName="checked">
                <Checkbox />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="录入制表用户"
                name="input_username"
                valuePropName="checked">
                <Checkbox />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label="自定义时间段"
                tooltip="允许生成报表时用户选择时间段"
                name="custom_time_range"
                valuePropName="checked">
                <Checkbox />
              </Form.Item>
            </Col>
          </Row>

          {isDayReport && autoGenerateItems}

        </Form>
      </Modal>
    )
  }
}

export default SettingDialog